#!coding=utf-8
from django.shortcuts import *
from enterprise_basic_information.models import *
from enterprise_pollution_prevention.models import *
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponseRedirect
from models import Park,LogManage
import json
from enterprise_pollute.models import FeaturesPollu
from enterprise_chemicals.models import Chemicals,Product,Materials,InterMeditatesPro
from enterprise_facilities.models import Production,StorageTank,ProductArea,StorageArea
from enterprise_basic_information.models import Enterprise
from enterprise_chemicals.models import Ingredients,IngredientsType,ChemicalsRelative
from util.form_util import *
from django.db.models import Q
import sys
reload(sys)
sys.setdefaultencoding('utf8')

def companyEditFill(request,id,fill_key):
    enter=Enterprise.objects.get(id=id)
    enter_fill=Enter_fill.objects.get(fill_key=fill_key)
    fillModel=Fill.objects.get(enterprise=enter,enter_fill=enter_fill)
    fillModel.status="submit"
    fillModel.save()
    request.session['fill']=fillModel
    return HttpResponseRedirect('/park/companyfill/')
def logs(request):
    admin = request.session.get('admin',None)

    if not admin:
        return HttpResponse('当前用户信息错误')

    logs = LogManage.objects.order_by('-date').all()

    paginator = Paginator(logs, 15)
    page = request.GET.get('page')
    try:
        contacts = paginator.page(page)
    except PageNotAnInteger:
        contacts = paginator.page(1)
    except EmptyPage:
        contacts = paginator.page(paginator.num_pages)
    params={  'contacts' : contacts ,
              'paginator':paginator,
            }
    return render_to_response('park/log_list.html',params,context_instance=RequestContext(request))

# Create your views here.
def park(request):
    admin = request.session.get('admin',None)

    if not admin:
        return HttpResponse('当前用户信息错误')

    park = Park.objects.filter(id=admin.park.id)
    # admin.park
    if len(park) > 0:
        return render_to_response('park/park_info_detail.html', { 'p':park[0] }, context_instance=RequestContext(request))
    else:
        p = Park()
        p.user = admin
        p.save()
        return HttpResponseRedirect('/park/edit/')

def map(request):
    admin = request.session.get('admin', None)

    if not admin:
        return HttpResponse('当前用户信息错误')

    park = request.session.get('park', None)

    es = Enterprise.objects.filter(park = park)
    ps = ProductArea.objects.all()
    ss = StorageArea.objects.all()

    tmp = []

    for e in es:
        eData = {}
        eData['e'] = e

        _points,_centerPoint,_extent = e.getGeoData()

        if not _points:
            _points = '[]'

        if not _centerPoint:
            _centerPoint = '[]'

        if not _extent:
            _centerPoint = '[]'

        eData['points'] = _points
        eData['center'] = _centerPoint
        eData['extent'] = _extent

        eData['ps'] = ps.filter(mapdata__isnull=False, enterprise=e)
        eData['ss'] = ss.filter(mapdata__isnull=False, enterprise=e)

        tmp.append(eData)
    print tmp[0]['ps'][0].mapdata.getObj()['center_point']
    return render_to_response('park/park_map.html', { 'p':park, 'geo_data':tmp },context_instance=RequestContext(request))

@csrf_exempt
def mapEdit(request):
    admin = request.session.get('admin', None)

    if not admin:
        return HttpResponse('当前用户信息错误')

    if request.method == 'GET':
        park = request.session.get('park', None)

        return render_to_response('park/park_map_edit.html', { 'p':park },context_instance=RequestContext(request))

    if request.method == 'POST':
        
        park = request.session.get('park', None)

        park.geo_center_point = request.POST.get('geo_center_point','')
        park.geo_points = request.POST.get('geo_points','')
        park.geo_extent = request.POST.get('geo_extent','')
        park.save()

        request.session['park'] = park

        return render_to_response('park/park_map_edit.html', { 'p':park },context_instance=RequestContext(request))

@csrf_exempt
def edit(request):
    admin = request.session.get('admin',None)
    park = request.session.get('park',None)

    if request.method == 'GET':
        p = request.session.get('park',None)
        return render_to_response('park/park_info_edit.html', { 'p':p },context_instance=RequestContext(request))
    else:
        p = Park.objects.get(id=admin.park.id)
        auto_wear(request, p, 'park', 'Park')
        p.save()
        return HttpResponseRedirect('/park/mypark/')

@csrf_exempt
def companyList(request):
    park = request.session.get('park',None)
    lists=Enterprise.objects.filter(park=park)
    paginator = Paginator(lists, 10)
    page = request.GET.get('page')
    try:
        contacts = paginator.page(page)
    except PageNotAnInteger:
        contacts = paginator.page(1)
    except EmptyPage:
        contacts = paginator.page(paginator.num_pages)
    params={  'contacts' : contacts ,
              'paginator':paginator,
              'count':len(lists),
              }
    return render_to_response('park/company_list.html',params,context_instance=RequestContext(request))

@csrf_exempt
def submitfill(request):
    park_id=request.POST['park_id']
    start_time=request.POST['start_time']
    end_time=request.POST['end_time']
    park=Park.objects.get(id=park_id)
    key=str(start_time)
    enter_fill_list=Enter_fill.objects.filter()
    for enter in enter_fill_list:
        if enter.fill_key==key:
            return HttpResponseRedirect('/park/filladd/?message=error')
    ent_fill=Enter_fill.objects.create(park=park,fill_starttime=start_time,fill_endtime=end_time,fill_key=key)

    List=Enterprise.objects.filter(park=park)
    for ent in List:
        fill=Fill.objects.create(enterprise=ent,enter_fill=ent_fill,status='no_submit')
        create(fill,ent)
    return HttpResponseRedirect('/park/companyfill/')

def create(fill,ent):
    Application_status.objects.create(fill=fill,enterprise=ent,app_name="企业基本信息",app_status="未确认",order=1,app_url='/basic/detail/')
    Application_status.objects.create(fill=fill,enterprise=ent,app_name="环境保护目标信息",app_status="未确认",order=2,app_url='/basic/prevention/detail/')
    Application_status.objects.create(fill=fill,enterprise=ent,app_name="法律法规遵守情况",app_status="未确认",order=3,app_url='/basic/law/detail/')
    Application_status.objects.create(fill=fill,enterprise=ent,app_name="原辅料信息",app_status="未确认",order=4,app_url='/chemicals/materialList')
    Application_status.objects.create(fill=fill,enterprise=ent,app_name="中间产品信息",app_status="未确认",order=5,app_url='/chemicals/impList')
    Application_status.objects.create(fill=fill,enterprise=ent,app_name="产品信息",app_status="未确认",order=6,app_url='/chemicals/productList')
    Application_status.objects.create(fill=fill,enterprise=ent,app_name="生产区",app_status="未确认",order=7,app_url='/facilities/productAreaList/')
    Application_status.objects.create(fill=fill,enterprise=ent,app_name="贮罐区",app_status="未确认",order=8,app_url='/facilities/storageAreaList/')
    Application_status.objects.create(fill=fill,enterprise=ent,app_name="污染物基本信息",app_status="未确认",order=9,app_url='/pollution/prevention/detail/')
    Application_status.objects.create(fill=fill,enterprise=ent,app_name="特征化学污染物信息",app_status="未确认",order=10,app_url='/pollution/release_transfer/transferList/')

def filladd(request):
    park = request.session.get('park',None)
    message=request.GET.get('message')
    params={'park':park,
       'message':message,
       }
    return render_to_response('park/fill_add.html',params,context_instance=RequestContext(request))


@csrf_exempt
def submitsearchfill(request):
    park = request.session.get('park',None)
    enterf=Enter_fill.objects.filter(park=park)
    fill=request.POST['fill']
    if fill=='0':
        return HttpResponseRedirect('/park/fill_add/')
    else:
        enterfill=Enter_fill.objects.filter(park=park,fill_key=fill)
        paginator = Paginator(enterfill, 10)
        page = request.GET.get('page')
        try:
            contacts = paginator.page(page)
        except PageNotAnInteger:
            contacts = paginator.page(1)
        except EmptyPage:
            contacts = paginator.page(paginator.num_pages)
        params={  'contacts' : contacts ,
                  'paginator':paginator,
                  'count':len(enterfill),
                  'enterfill':enterf,
                  }
        return render_to_response('park/company_fill.html',params,context_instance=RequestContext(request))

def companyfill(request):
    park = request.session.get('park',None)
    enterfill=Enter_fill.objects.filter(park=park)
    paginator = Paginator(enterfill, 10)
    page = request.GET.get('page')
    try:
        contacts = paginator.page(page)
    except PageNotAnInteger:
        contacts = paginator.page(1)
    except EmptyPage:
        contacts = paginator.page(paginator.num_pages)
    params={  'contacts' : contacts ,
              'paginator':paginator,
              'count':len(enterfill),
              'enterfill':enterfill,

              }
    return render_to_response('park/company_fill.html',params,context_instance=RequestContext(request))
@csrf_exempt
def companyDetail(request,param):
    _enterPrise=Enterprise.objects.get(id=param)
    basic_list = Enterprise_basic_information.objects.filter(enterprise = _enterPrise)
    basic = None
    if len(basic_list) > 0:
        basic = basic_list[0]
        geo_center_point = basic.geo_center_point 
        if geo_center_point:
            basic.geo_center_point = json.loads(geo_center_point)
    params={  'basic' : basic ,
              'name':_enterPrise.name,
              }
    return render_to_response('park/company_detail.html',params,context_instance=RequestContext(request))
@csrf_exempt
def companyEdit(request,param):
    enterprise=Enterprise.objects.get(id=param)
    params={  'enterprise' : enterprise ,
              }
    return render_to_response('park/company_info_edit.html',params,context_instance=RequestContext(request))

def companyDelete(request,param):
    Enterprise.objects.get(id=param).delete()
    return HttpResponseRedirect('/park/companyList/')
@csrf_exempt
def companyAdd(request):
    return render_to_response('park/company_info_edit.html',context_instance=RequestContext(request))

@csrf_exempt
def submitEidtPark(request):
    username=request.POST.get('username')
    password=request.POST.get('password')
    enterprise_id=request.POST.get('enterprise_id')
    enterprise_name=request.POST.get('enterprise_name')
    disable=request.POST.get('disable')
    park = request.session.get('park',None)
    if not disable:
        disable='0'
    if not enterprise_id:
        user=User()
        user.username=username
        user.password=password
        user.category=1
        user.save()
        enterprise=Enterprise()
        enterprise.name=enterprise_name
        enterprise.disable=disable
        enterprise.user=user
        enterprise.park=park
        enterprise.save()

        enetr_fill=Enter_fill.objects.filter(park=park)
        status='no_submit'
        for ef in enetr_fill:
            Fill.objects.create(enterprise=enterprise,status=status,enter_fill=ef)

        fill_list=Fill.objects.filter(enterprise=enterprise)
        for fill in fill_list:
            create(fill,enterprise)
    else:
        enterprise=Enterprise.objects.get(id=enterprise_id)
        enterprise.name=enterprise_name
        enterprise.disable=disable
        enterprise.save()
        user=User.objects.get(id=enterprise.user.id)
        user.username=username
        user.password=password
        user.save()
    return HttpResponseRedirect('/park/companyList/')

@csrf_exempt
def preventionList(request):
    park = request.session.get('park',None)
    if "name" in request.GET:
        lists=Enterprise.objects.filter(name__contains=request.GET["name"],park=park)
    else:
        lists=Enterprise.objects.filter(park=park)
    paginator = Paginator(lists, 15)
    page = request.GET.get('page')
    try:
        contacts = paginator.page(page)
    except PageNotAnInteger:
        contacts = paginator.page(1)
    except EmptyPage:
        contacts = paginator.page(paginator.num_pages)
    params={  'contacts' : contacts ,
              'paginator':paginator,
              "coms":lists
              }
    return render_to_response('park/preventionList.html',params,context_instance=RequestContext(request))   


@csrf_exempt
def  lawyerList(request):
    lists=Enterprise.objects.filter()
    paginator = Paginator(lists, 15)
    page = request.GET.get('page')
    try:
        contacts = paginator.page(page)
    except PageNotAnInteger:
        contacts = paginator.page(1)
    except EmptyPage:
        contacts = paginator.page(paginator.num_pages)
    params={  'contacts' : contacts ,
              'paginator':paginator,
              }
    return render_to_response('park/lawyer_list.html',params,context_instance=RequestContext(request))
@csrf_exempt
def companyLawyer(request,param):
    _enterPrise=Enterprise.objects.get(id=param)
    list_1=Licenses.objects.filter(enterprise = _enterPrise,type=1)
    list_2=Licenses.objects.filter(enterprise = _enterPrise,type=2)
    list_3=Licenses.objects.filter(enterprise = _enterPrise,type=3)
    list_4=Licenses.objects.filter(enterprise = _enterPrise,type=4)
    list_5=Licenses.objects.filter(enterprise = _enterPrise,type=5)
    list_6=Licenses.objects.filter(enterprise = _enterPrise,type=6)
    list_7=Licenses.objects.filter(enterprise = _enterPrise,type=7)
    remark_1=Law_remark.objects.filter(enterprise=_enterPrise,type=1)
    remark_2=Law_remark.objects.filter(enterprise=_enterPrise,type=2)
    files_1=Law_files.objects.filter(enterprise=_enterPrise,type=1)
    files_2=Law_files.objects.filter(enterprise=_enterPrise,type=2)
    files_3=Law_files.objects.filter(enterprise=_enterPrise,type=3)
    poll_1=Emissions.objects.filter(enterprise=_enterPrise,type=1)
    poll_2=Emissions.objects.filter(enterprise=_enterPrise,type=2)
    poll_3=Emissions.objects.filter(enterprise=_enterPrise,type=3)
    clean=Cleaner_production.objects.filter(enterprise=_enterPrise)
    template='park/basic_laws_detail.html'
    if remark_1:
        remark_1=remark_1[0]
    if remark_2:
        remark_2=remark_2[0]
    if clean:
        clean=clean[0]
    emergencies = Environmental_emergencies.objects.filter(enterprise = _enterPrise)
    if emergencies:
        emer = emergencies[0]
    else:
        emer = Environmental_emergencies()

    params={  'list_1' : list_1,'one_length':len(list_1) ,
              'list_2':list_2,'two_length':len(list_2),
              'list_3':list_3,'three_length':len(list_3),
              'list_4':list_4,'four_length':len(list_4),
              'list_5':list_5,'five_length':len(list_5),
              'list_6':list_6,'six_length':len(list_6),
              'list_7':list_7,'seven_length':len(list_7),
              'poll_1':poll_1,'poll_2':poll_2,'poll1_length':len(poll_1),
              'poll_3':poll_3,'poll2_length':len(poll_2),
              'emer':emer,'poll3_length':len(poll_3),
              'remark_1':remark_1,
              'remark_2':remark_2,
              'files_1':files_1,
              'files_2':files_2,
              'files_3':files_3,
              'file1_length':len(files_1),
              'file2_length':len(files_2),
              'file3_length':len(files_3),
              'clean':clean,
              'name':_enterPrise.name
              }
    return render_to_response(template,params ,context_instance=RequestContext(request))
@csrf_exempt
def gasandwaterDetail(request,param): 
    _enterPrise=Enterprise.objects.get(id=param)
    gas_list = Gas_environment.objects.filter(enterprise = _enterPrise)
    gas = Gas_environment();
    gdetails = []
    if gas_list:
        gas = gas_list[0]
        gdetails =gas.gas_environment_detail_set.all()
        
    water_list = Water_environment.objects.filter(enterprise = _enterPrise)
    water = Water_environment();
    wdetails = []
    if water_list:
        water = water_list[0]
        wdetails =water.water_environment_detail_set.all()
            
    return render_to_response('park/basic_WaterGas_detail.html',{"gas":gas,"water":water,"gdetails":gdetails,"wdetails":wdetails,'name':_enterPrise.name,},context_instance=RequestContext(request))


@csrf_exempt
def pollutiondetaillist(request):
    if "name" in request.GET:
        lists=Enterprise.objects.filter(name__contains=request.GET["name"])
    else:
        lists=Enterprise.objects.filter()
    paginator = Paginator(lists, 15)
    page = request.GET.get('page')
    try:
        contacts = paginator.page(page)
    except PageNotAnInteger:
        contacts = paginator.page(1)
    except EmptyPage:
        contacts = paginator.page(paginator.num_pages)
    params={  'contacts' : contacts ,
              'paginator':paginator,
              }
    return render_to_response('park/pollutiondetaillist.html',params,context_instance=RequestContext(request))

@csrf_exempt
def release_transferList(request):
    
    park = request.session.get('park',None)
    lists=Enterprise.objects.filter(park=park)
    _enterPrise = lists;
    if "com" in request.GET and request.GET["com"]:
        _enterPrise=Enterprise.objects.filter(name__contains=request.GET["com"],park=park)
    ens = []    
    for id in  _enterPrise:   
        ens.append(id)
        
    query = Q(enterprise__in = ens)
    if "key_environmental_name" in request.GET and request.GET["key_environmental_name"]:
        query = query & Q(key_environmental_name = request.GET["key_environmental_name"])
        
    if "key_environmental_kind" in request.GET and request.GET["key_environmental_kind"]:
        query = query & Q(key_environmental_kind = request.GET["key_environmental_kind"])
    if "orderby" in request.GET and request.GET["orderby"]: 
        if request.GET["orderby"] == 'key_environmental_name':
            basic_list = pollutant_transfer_situation.objects.filter(query).order_by("key_environmental_name")
        else:
            basic_list = pollutant_transfer_situation.objects.filter(query).order_by("enterprise__name")
    else:
        basic_list = pollutant_transfer_situation.objects.filter(query)   
    try:
        paginator = Paginator(basic_list, 10)
        page = request.GET.get('page')
        basic_list = paginator.page(page)
    except PageNotAnInteger:
        basic_list = paginator.page(1)
    except EmptyPage:
        basic_list = paginator.page(paginator.num_pages)
    return  render_to_response('park/release_transferList.html',{"list":basic_list,"coms":lists, 'paginator':paginator },context_instance=RequestContext(request))


def transferDetail(request):
    id = request.GET["id"]
    basic = pollutant_transfer_situation.objects.get(id = id)
    solidList = Transfer_solid_waste_unit.objects.filter(situation = basic)
    return  render_to_response('park/transferDetail.html',{"basic":basic,"solidList":solidList},context_instance=RequestContext(request))



@csrf_exempt
def other_chemicalsList(request):
    park = request.session.get('park',None)
    lists=Enterprise.objects.filter(park=park)
    _enterPrise = lists;
    if "com" in request.GET and request.GET["com"]:
        _enterPrise=Enterprise.objects.filter(name__contains=request.GET["com"],park=park)
    ens = []    
    for id in  _enterPrise:   
        ens.append(id)    
    query = Q(enterprise__in = ens)
    if "chemical_pollutants_name" in request.GET and request.GET["chemical_pollutants_name"]:
        query = query & Q(chemical_pollutants_name = request.GET["chemical_pollutants_name"])
    if "emissions" in request.GET and request.GET["emissions"]:
        query = query & Q(emissions = request.GET["emissions"]) 
        
    if "orderby" in request.GET and request.GET["orderby"]:
        if request.GET["orderby"] == "com":
            basic_list = other_specific_information.objects.filter(query).order_by("enterprise__name")
        else:           
            basic_list = other_specific_information.objects.filter(query).order_by(request.GET["orderby"])
    else:
        basic_list = other_specific_information.objects.filter(query)
    try:
        paginator = Paginator(basic_list, 10)
        page = request.GET.get('page')
        basic_list = paginator.page(page)
    except PageNotAnInteger:
        basic_list = paginator.page(1)
    except EmptyPage:
        basic_list = paginator.page(paginator.num_pages)
    return  render_to_response('park/chemicalsList.html',{"list":basic_list,"coms":lists, 'paginator':paginator,'en':_enterPrise},context_instance=RequestContext(request))

def industry_echarts(request):
    return render_to_response('park/industry_echarts.html',context_instance=RequestContext(request))


def zc(request):
    park = request.session.get('park',None)
    basic_list=Enterprise.objects.filter(park=park)
    params={'list':basic_list}
    return render_to_response('park/data_detail/normalPollutionSchedule.html',params,context_instance=RequestContext(request))

def tz(request):
    park = request.session.get('park',None)
    basic_list=Enterprise.objects.filter(park=park)
    params={'list':basic_list}
    return render_to_response('park/data_detail/TZPollutionSchedule.html',params,context_instance=RequestContext(request))


def mx(request):
    return render_to_response('park/data_detail/datadetail.html',context_instance=RequestContext(request))


def mydata(name,cas,chnumber_x,chnumber_d,cr_type):
    chemicalsRelative=None
    cheCount=None
    chemicalsRelativeList=[]
    lngredientsList=Ingredients.objects.filter(e_name=name,e_code=cas)
    if lngredientsList:
        for ingredients in lngredientsList:
            cheCount=ingredients.e_shechun
            if cheCount:
                cheCount=int(cheCount)
            if chnumber_x and chnumber_d:
                chnumber_x=int(chnumber_x)
                chnumber_d=int(chnumber_d)
                if (cheCount-chnumber_x)>0:
                    if (chnumber_d-cheCount)>0:
                        chemicalsRelative=ChemicalsRelative.objects.filter(cr_type=cr_type,igds_entity=ingredients)
                        chemicalsRelativeList.append(chemicalsRelative)
            else:
                chemicalsRelative=ChemicalsRelative.objects.filter(cr_type=cr_type,igds_entity=ingredients)
                chemicalsRelativeList.append(chemicalsRelative)
        return chemicalsRelativeList


def gettypeByChem():
    return None
"""
查询
"""
@csrf_exempt
def serachDetail(request):
    name=request.POST.get('name')
    cas=request.POST.get('cas')
    time=request.POST.get('time')
    serachType=request.POST.getlist('serachType')
    chnumber_x=request.POST.get('chnumber_x')
    chnumber_d=request.POST.get('chnumber_d')
    cTnumber_x=request.POST.get('cTnumber_x')
    cTnumber_d=request.POST.get('cTnumber_d')
    ent_name=request.POST.get('ent_name')
    ent_code=request.POST.get('ent_code')
    register_add0=request.POST.get('register_add0')
    register_add1=request.POST.get('register_add1')
    register_add2=request.POST.get('register_add2')
    industry_code=request.POST.get('industry_code')
    enterprise_type=request.POST.get('enterprise_type')
    industry_park_time=request.POST.get('industry_park_time')
    industry_park_name=request.POST.get('industry_park_name')
    industry_park_code=request.POST.get('industry_park_code')
    enterprises=[]
    if ent_name:
        enterprise=Enterprise.objects.get(name=ent_name)
        enterprises.append(enterprise)
    else:
        if len(serachType)>0:
            for se in serachType:
                if se=='1':
                    cr_type=IngredientsType.objects.get(name="原辅料信息")
                    chemicalsRelativeList=mydata(name,cas,chnumber_x,chnumber_d,cr_type)
                    if chemicalsRelativeList:
                        for chemicalsRelative in chemicalsRelativeList:
                            for c in chemicalsRelative:
                                materials=Materials.objects.get(id=c.che_entity)
                                enterprises.append(materials.enterprise)
                    cr_type=IngredientsType.objects.get(name="中间产品信息")
                    chemicalsRelativeList=mydata(name,cas,chnumber_x,chnumber_d,cr_type)
                    if chemicalsRelativeList:
                        for chemicalsRelative in chemicalsRelativeList:
                            for c in chemicalsRelative:
                                interMeditatesPro=InterMeditatesPro.objects.get(id=c.che_entity)
                                enterprises.append(interMeditatesPro.enterprise)
                    cr_type=IngredientsType.objects.get(name="产品信息")
                    chemicalsRelativeList=mydata(name,cas,chnumber_x,chnumber_d,cr_type)
                    if chemicalsRelativeList:
                        for chemicalsRelative in chemicalsRelativeList:
                            for c in chemicalsRelative:
                                product=Product.objects.get(id=c.che_entity)
                                enterprises.append(product.enterprise)
                    if cTnumber_x and cTnumber_d:
                        cTnumber_x=int(cTnumber_x)
                        cTnumber_d=int(cTnumber_d)
                        enterprise_list=Enterprise.objects.all()
                        count=0
                        for enterprise in enterprise_list:
                            count=enterprise.getMaterialsChem()+enterprise.getInterMeditatesProchem()+enterprise.getProductchem()
                            if (count-cTnumber_x)>0:
                                if (cTnumber_d-count)>0:
                                    enterprises.append(enterprise)
                    break
                if se=='2':
                    cr_type=IngredientsType.objects.get(name="原辅料信息")
                    chemicalsRelativeList=mydata(name,cas,chnumber_x,chnumber_d,cr_type)
                    if chemicalsRelativeList:
                        for chemicalsRelative in chemicalsRelativeList:
                            for c in chemicalsRelative:
                                materials=Materials.objects.get(id=c.che_entity)
                                enterprises.append(materials.enterprise)
                if se=='3':
                    cr_type=IngredientsType.objects.get(name="中间产品信息")
                    chemicalsRelativeList=mydata(name,cas,chnumber_x,chnumber_d,cr_type)
                    if chemicalsRelativeList:
                        for chemicalsRelative in chemicalsRelativeList:
                            for c in chemicalsRelative:
                                interMeditatesPro=InterMeditatesPro.objects.get(id=c.che_entity)
                                enterprises.append(interMeditatesPro.enterprise)
                if se=='4':
                    cr_type=IngredientsType.objects.get(name="产品信息")
                    chemicalsRelativeList=mydata(name,cas,chnumber_x,chnumber_d,cr_type)
                    if chemicalsRelativeList:
                        for chemicalsRelative in chemicalsRelativeList:
                            for c in chemicalsRelative:
                                product=Product.objects.get(id=c.che_entity)
                                enterprises.append(product.enterprise)
        else:
            error="请选择查询种类！"
            return render_to_response('park/data_detail/datadetail.html',{'error':error},context_instance=RequestContext(request))
    list_1=request.POST.getlist('list')
    count=len(list_1)
    if not enterprises:
        params={'list':list_1,'count':count+8,
                'info':"无符合查询条件的企业"}
    else:
        enterprises=list(set(enterprises))
        params={'list':list_1,'count':count+8,
                'enterpriseList':enterprises}
    return render_to_response('park/data_detail/datadetail.html',params,context_instance=RequestContext(request))


@csrf_exempt
def chemicalsList(request,param):
    _enterPrise=Enterprise.objects.get(id=param)
    if request.method == "POST":
        if request.POST["create_time"]:
            create_time = request.POST["create_time"]
            create_time = create_time.split("-")
            year = create_time[0]
            month = create_time[1]
            basic_list = other_specific_information.objects.filter(enterprise = _enterPrise,create_time__year = year,create_time__month = month)
        else:
            basic_list = other_specific_information.objects.filter(enterprise = _enterPrise)
    else:
        basic_list = other_specific_information.objects.filter(enterprise = _enterPrise)
    try:
        paginator = Paginator(basic_list, 10)
        page = request.GET.get('page')
        basic_list = paginator.page(page)
    except PageNotAnInteger:
        basic_list = paginator.page(1)
    except EmptyPage:
        basic_list = paginator.page(paginator.num_pages)
    return  render_to_response('park/chemicalsList.html',{"list":basic_list, 'paginator':paginator,'en':_enterPrise},context_instance=RequestContext(request))
@csrf_exempt
def preventionDetail(request,param):
    _enterPrise=Enterprise.objects.get(id=param)
    basic_list = Pollution_control_information.objects.filter(enterprise = _enterPrise)
    basic = ""
    if len(basic_list) > 0:
        basic = basic_list[0]
    return  render_to_response('park/pollutiondetail.html', {  'basic' : basic,'name':_enterPrise.name, },context_instance=RequestContext(request))

def chemicalDetail(request):
    id = request.GET["id"]
    #_enterPrise=Enterprise.objects.get(id=request.GET["en"])
    basic = other_specific_information.objects.get(id = id)
    return  render_to_response('park/chemicalDetail.html',{"basic":basic,},context_instance=RequestContext(request))

@csrf_exempt
def submitStatistics(request):
    admin=request.session['admin']
    _enterpriseList=Enterprise.objects.filter(park=admin.park)
    type=request.POST['types']
    dict={}
    array=[]
    array2=[]
    # 中间产品
    if type=='1':
        for ent in _enterpriseList:
            chemicalsList=InterMeditatesPro.objects.filter(enterprise=ent)
            number=len(chemicalsList)
            name=ent.name
            array.append(name)
            array2.append(number)
        dict['name']=array
        dict['number']=array2
        # 产品信息
    if type=='2':
        for ent in _enterpriseList:
            productList=Product.objects.filter(enterprise=ent)
            number=len(productList)
            name=ent.name
            array.append(name)
            array2.append(number)
        dict['name']=array
        dict['number']=array2
        # 原辅料
    if type=='3':
        for ent in _enterpriseList:
            materialsList=Materials.objects.filter(enterprise=ent)
            number=len(materialsList)
            name=ent.name
            array.append(name)
            array2.append(number)
        dict['name']=array
        dict['number']=array2
        # 生产区设备
    if type=='4':
        for ent in _enterpriseList:
            productionList=ProductArea.objects.filter(enterprise=ent)
            number=len(productionList)
            name=ent.name
            array.append(name)
            array2.append(number)
        dict['name']=array
        dict['number']=array2
# 贮罐区设备
    if type=='5':
        for ent in _enterpriseList:
            storageTankList=StorageArea.objects.filter(enterprise=ent)
            number=len(storageTankList)
            name=ent.name
            array.append(name)
            array2.append(number)
        dict['name']=array
        dict['number']=array2
# 特征化学污染物
    if type=='7':
        for ent in _enterpriseList:
            other_specific_informationList=FeaturesPollu.objects.filter(enterprise=ent)
            number=len(other_specific_informationList)
            name=ent.name
            array.append(name)
            array2.append(number)
        dict['name']=array
        dict['number']=array2
# 总量
    if type=='8':
        num=0
        num1=0
        num2=0
        num3=0
        num4=0
        num6=0
        for ent in _enterpriseList:
            chemicalsList=InterMeditatesPro.objects.filter(enterprise=ent)
            num=num+len(chemicalsList)
            productList=Product.objects.filter(enterprise=ent)
            num1=num1+len(productList)
            materialsList=Materials.objects.filter(enterprise=ent)
            num2=num2+len(materialsList)
            productionList=Production.objects.filter(enterprise=ent)
            num3=num3+len(productionList)
            storageTankList=StorageTank.objects.filter(enterprise=ent)
            num4=num4+len(storageTankList)
            other_specific_informationList=FeaturesPollu.objects.filter(enterprise=ent)
            num6=num6+len(other_specific_informationList)

        array.append("中间产品")
        array2.append(num)
        array.append("产品信息")
        array2.append(num1)
        array.append("原辅料输入")
        array2.append(num2)
        array.append("生产区设备")
        array2.append(num3)
        array.append("贮罐区设备")
        array2.append(num4)
        array.append("特征化学污染物")
        array2.append(num6)
        dict['name']=array
        dict['number']=array2

    return HttpResponse(json.dumps(dict,ensure_ascii=False))